/*
 * @Author: fishroom
 * @Date: 2022-09-27 17:31:29
 * @LastEditTime: 2023-01-06 17:22:35
 * @FilePath: \koa\app\index.ts
 */
import dotenv from "Dotenv";
dotenv.config();
import db from "./db";
db();
import Koa from "koa";
import cors from "koa2-cors";
import router from "./router/admin";
import { Server } from "http";
import AccessLogMiddleWare from "./middleware/AccessLogMiddleWare";
import { koaSwagger } from "koa2-swagger-ui";
import bodyPars from "koa-body";
import path from "path";
import Koa_Session from "koa-session";
import sessionConfig from "./config/session";

import { createServer } from "http";
import { Server as ServerIo, Socket } from "socket.io";
import staticKoa from "koa-static";

import ChitchatUser from "./socketHandler/ChitchatUser";
import sendHandler from "./socketHandler/sendHandler";
import loginHandler from "./socketHandler/loginHandler";
import friendHandler from "./socketHandler/friendHandler";
import ChitchatGroup from "./socketHandler/ChitchatGroup";
import socketGroupServer from "./server/socketServer/socketGroupServer";

//这个是配合signed属性的签名key
const session_signed_key = ["appletSystem"];

const app = new Koa();
// session 密钥
app.keys = session_signed_key;
// 解析请求
var bodyParser = require("koa-bodyparser");

// 使用session
app.use(Koa_Session(sessionConfig, app));

// 使用请求解析配置
app.use(
  bodyPars({
    multipart: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      uploadDir: path.join(__dirname, "../static"), // 上传目录 uploadDir:
      keepExtensions: true, //保留文件扩展名
    },
  })
);
app.use(staticKoa(path.join(__dirname, "../static")));
//
app.use(bodyParser());
app.use(cors());
app.use(
  koaSwagger({
    routePrefix: "/swagger", // host at /swagger instead of default /docs
    swaggerOptions: {
      url: "/swagger.json", // example path to json 其实就是之后swagger-jsdoc生成的文档地址
    },
  })
);
app.use(AccessLogMiddleWare).use(router.routes());
const swagger = require("./util/swagger.js");
app.use(swagger.routes()).use(swagger.allowedMethods());

const httpServer = createServer(app.callback());
const io = new ServerIo(httpServer, {
  cors: {
    origin: "*",
  },
});

const groupChitchat: Map<number, ChitchatGroup> = new Map();
// 从数据库拿出所有群对象
(async () => {
  const groups: Array<any> = await socketGroupServer.getGroupsAll();
  groups.forEach((item, index) => {
    item.member = new Map(Object.entries(JSON.parse(item.dataValues.member || "{}")));
    groupChitchat.set(item.dataValues.group_id, item.dataValues);
  });
})();

const userChitchat: Map<string, ChitchatUser> = new Map();

const { login } = loginHandler(io, userChitchat, groupChitchat);
let { sendMessage, sendMessageById, sendMessageGroup } = sendHandler(
  io,
  userChitchat,
  groupChitchat
);
let { addFriendById, addGroupById } = friendHandler(io, userChitchat, groupChitchat);
io.on("connection", (socket: Socket) => {
  socket.on("login", login);
  socket.on("sendMessage", sendMessage);
  socket.on("sendMessageById", sendMessageById);
  socket.on("sendMessageGroup", sendMessageGroup);
  socket.on("addFriendById", addFriendById);
  socket.on("addGroupById", addGroupById);
});

const run = (port: any): Server => {
  return httpServer.listen(port);
};
export default run;
